#include <arpa/inet.h>
#include <asm-generic/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>

#include "tcp_init.h"

int tcp_init(const char *ip, const char *port, int *sockfd) {
  *sockfd = socket(AF_INET, SOCK_STREAM, 0);
  struct sockaddr_in server_addr;
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = inet_addr(ip);
  server_addr.sin_port = htons(atoi(port));

  int reuse = 1;
  int reuse_ret =
      setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  if (reuse_ret == -1) {
    perror("setsockopt");
  }

  int bind_ret =
      bind(*sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
  if (bind_ret == -1) {
    perror("bind");
  }

  listen(*sockfd, 10);

  return 0;
}
